import { useState, useMemo } from 'react';
import { Checkbox } from 'antd';
import PopoverComponent from './PopoverComponent';
import MultilingualInput from '../../.././../../MultilingualInput';
import '../style.less';

export default function Termination(props) {
    const { value, onChange } = props;
    const [popoverVisible, setPopoverVisible] = useState(false);

    const buttonItem = useMemo(() => {
        return value?.find((item) => item?.action == 'cancel');
    }, [value]);

    const onCheckChange = (e: { target: { checked: boolean; }; }) => {
        const _value = value?.map((item) => {
            if (item?.action == 'cancel') {
                return {
                    ...item,
                    enable: e?.target?.checked,
                }
            } else {
                return item;
            };
        });
        onChange(_value);
    };

    const onTextChange = () => {
        const _value = value?.map((item) => {
            if (item?.action == 'cancel') {
                return {
                    ...item,
                    enable: !buttonItem?.enable,
                }
            } else {
                return item;
            };
        });
        onChange(_value);
    };

    const onInputChange = (val: string) => {
        const _value = value?.map((item) => {
            if (item?.action == 'cancel') {
                return {
                    ...item,
                    name: val,
                }
            } else {
                return item;
            };
        });
        onChange(_value);
    };

    return (
        <div className='process-designer-button'>
            <Checkbox checked={buttonItem?.enable} onChange={onCheckChange} />
            <div className='process-designer-button-text' onClick={onTextChange} title='终止'>终止</div>
            {
                buttonItem?.enable
                &&
                <>
                    <MultilingualInput value={buttonItem?.name} onChange={onInputChange} />
                    <PopoverComponent
                        popoverVisible={popoverVisible}
                        setPopoverVisible={setPopoverVisible}
                        value={value}
                        onChange={onChange}
                        type='cancel'
                    />
                </>
            }
        </div>
    )
};